<script setup>
import Toast from '@vant/weapp/dist/toast/toast';
import newLoading from '@/components/newLoading/index.vue';
import myTextarea from '@/components/myTextarea.vue'
import { usePaintingStore } from '@/store';

import { getCategoryDetail } from "@/api/home";
import { getBackgroundImgTemplates, editImgUpload, imgAiBackgroundV2, getImageByTaskId } from "@/api/painting";


import { ref, nextTick, computed } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'


const paintingStore = usePaintingStore()


// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 查询参数
const queryParams = ref({
  model: 'DOUBAO'
})
// 提交数据
const queryData = ref({})
// 消耗算力
const expendNum = ref(0)

// 图片数量列表
const imgNumList = ref([])

// 绘图历史文案名称
const historyName = ref('generationBgcV2History')
// 绘图历史文案列表
const selectList = ref([])

const loading = ref(false);
const loadingRef = ref(null);

// 任务ID
const taskId = ref('')
let timer = null

// 场景列表
const sceneList = ref([])
// tabs选中
const tabCurrent = ref(0)
// 二级tabs选中
const twoTabCurrent = ref(0)




// 前往文案生成
function toPage() {
  const data = {
    baseImageUrl: queryParams.value.imageFileUrl,
  }
  uni.navigateTo({
    url: `/newEditionDraw/textContentProcessing/index?item=${JSON.stringify(data)}`
  })
}


// 开始生成
async function startFn() {
  clearInterval(timer);
  await verifyFn()
  loading.value = true
  await editImgUploadFn()
  imgAiBackgroundV2Fn()
}

// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    const data = {
      id: res.data.id,
      title: queryInfo.value.title,
      modelTypeId: queryItem.value.modelTypeId,
    }
    uni.navigateTo({
      url: `/draw/paintingResultPage/index?item=${JSON.stringify(data)}`,
    });
  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1]
    Toast.fail(errorMessage);
    loading.value = false
  }
}


// 发起生成背景任务
async function imgAiBackgroundV2Fn() {
  try {
    queryData.value = Object.assign({}, queryParams.value, queryData.value)
    const res = await imgAiBackgroundV2(queryData.value)
    paintingStore.setGenerationBgcV2Fn(queryData.value)
    tabCurrent.value === 1 && setHistoryContent()
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 5000);
  } catch (error) {
    loading.value = false
  }
}

// 上传原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await editImgUpload({
        type: 7,
        orgImg: queryParams.value.imageFileUrl
      })
      queryData.value.maskFileUrl = res.maskUrl
      queryData.value.imageFileUrl = res.orgImgUrl
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}


// 校验方法
function verifyFn() {
  return new Promise((resolve, reject) => {
    if (!queryParams.value.imageFileUrl) {
      Toast.fail('请上传图片')
      return reject()
    }
    resolve()
  })
}




// tabs切换
function tabsChange(e) {
  tabCurrent.value = e
  if (e === 0) {
    queryData.value.sceneType = Object.values(sceneList.value)[0][0]?.templateId
    const { prompt: scenePrompt, ...restParams } = queryData.value;
    queryData.value = { ...restParams };
  } else {
    const { sceneType: sceneTypeData, ...restData } = queryData.value;
    queryData.value = { ...restData };
  }
}


// 场景选择
function sceneItemClick(e) {
  queryData.value.sceneType = e.templateId
}


// 获取场景列表
const getBackgroundImgTemplatesFn = async () => {
  const res = await getBackgroundImgTemplates(7);
  sceneList.value = res.data;
  queryData.value.sceneType = Object.values(res.data)[0][0]?.templateId
};



// 数据转换
function dataConversion() {
  queryInfo.value.categoryParam.forEach(item => {
    if (item.title === 'imgNum') {
      imgNumList.value = item.data[0].title.split(',')
      queryData.value.num = imgNumList.value[0]
    } else if (item.title === 'expendNum') {
      expendNum.value = item.data[0].title
    }
  })
}


function imgLoad() {
  setTimeout(() => {
    Toast.clear()
  }, 300);
}

function prevwiewImage() {
  uni.navigateBack()
  // if (queryParams.value.imageFileUrl) {
  //   uni.previewImage({
  //     urls: [queryParams.value.imageFileUrl],
  //   })
  // } else {
  //   Toast.fail('请上传图片')
  // }
}



// 获取分类详情
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id)
  queryInfo.value = res.data
  dataConversion()
}

// 点击历史选中项
function clickSelectItem(item) {
  queryData.value.prompt = item.text
}


// 清除选中项
function clearSelectItem(item) {
  selectList.value = selectList.value.filter(i => i.text !== item.text)
  uni.setStorageSync(historyName.value, selectList.value)
}


// 存储文案历史记录
function setHistoryContent() {
  const existingIndex = selectList.value.findIndex(i => i.text === queryData.value.prompt);
  if (existingIndex !== -1) {
    selectList.value.splice(existingIndex, 1);
  }
  selectList.value.unshift({
    text: queryData.value.prompt,
    time: new Date().getTime()
  })
  uni.setStorageSync(historyName.value, selectList.value)
}


// 设置prompt
function setPrompt(text) {
  queryData.value.prompt = text
}


// 获取存储文案历史记录
function getHistoryContent() {
  selectList.value = uni.getStorageSync(historyName.value) || []
}

// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}


onUnload(() => {
  clearInterval(timer);
  loading.value = false
})


onLoad((e) => {
  if (e.item) {
    Toast.loading({
      message: '加载中...',
      duration: 0,
      forbidClick: true,
    });
    queryItem.value = JSON.parse(e.item)
    if (queryItem.value.imageFileUrl) {
      queryParams.value.imageFileUrl = queryItem.value.imageFileUrl
    }
  }
  getHistoryContent()
  getCategoryDetailFn()
  getBackgroundImgTemplatesFn()
})


defineExpose({
  setPrompt,
})


const textAreaStyle = {
  height: "300rpx",
}

const labelStyle = {
  fontWeight: "bold",
}
</script>

<template>
  <div class='generationBgc'>
    <NavBar>{{ queryInfo?.title }}</NavBar>

    <div class="container">
      <div class="title_box">
        上传图片
        <span class="text">（仅支持透明背景png图片）</span>
      </div>

      <div class="uploadImg" @click="prevwiewImage">
        <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" @load="imgLoad" mode="heightFix"
          class="imgSty" alt="">
        <div class="upload_btn" v-else>
          <i class="iconfont ai-icon-shangchuancankaotu"></i>
          <div class="text">上传图片</div>
        </div>
      </div>


      <div class="scene_box">
        <div class="tabs">
          <div class="tab" :class="{ active: tabCurrent === 0 }" @click="tabsChange(0)">场景生成</div>
          <div class="tab" :class="{ active: tabCurrent === 1 }" @click="tabsChange(1)">自定义生成</div>
        </div>
        <div class="scene_content">
          <van-tabs v-if="tabCurrent === 0" v-model:active='twoTabCurrent' animated :ellipsis="false" line-width="20"
            line-height="2" color="var(--a-main-color)" title-active-color="var(--a-main-color)"
            title-inactive-color="var(--a-two-text-color)">
            <van-tab v-for="(item, index) of sceneList" :title="index">
              <div class="scene_list" :class="{ gird: item.length > 8, noTowRows: item.length <= 4 }">
                <div class="scene_item" :class="{ active: queryData.sceneType === subItem.templateId }"
                  v-for="subItem of item" @click="sceneItemClick(subItem)">
                  <img class="scene_img" :src="subItem?.imgUrl" mode="aspectFill" />
                  <div> {{ subItem?.name }}</div>
                </div>
              </div>
            </van-tab>
          </van-tabs>

          <div class="textarea" v-else>
            <myTextarea v-model="queryData.prompt" keyName="text" :selectList="selectList"
              @clearSelectItem="clearSelectItem" @clickSelectItem="clickSelectItem" label="输入背景描述词（选填）"
              :labelStyle="labelStyle" :textAreaStyle="textAreaStyle" placeholder="输入画面描述，例如：阳光明媚2，一个男孩站在大树下面，白色衬衫">
            </myTextarea>
            <div class="ai_create_btn" @click="toPage" v-if="queryParams.imageFileUrl">
              文案生成
              <i class="iconfont ai-icon-suiji"></i>
            </div>
          </div>

        </div>

      </div>




      <div class="title_box">选择生成张数</div>
      <div class="imgNumList">
        <div class="imgNum_item" :class="{ active: queryData.num === item }" v-for="item of imgNumList"
          @click="queryData.num = item">
          {{ item }}
        </div>
      </div>

    </div>
    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <myDrawButton :expendNum="expendNum * queryData.num" @click="startFn">开始生成</myDrawButton>
      </div>
    </div>
  </div>
  <van-toast id="van-toast" />
  <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待10秒']" @close="loadingClose">
  </newLoading>
</template>

<style lang='scss' scoped>
::v-deep {
  .van-tabs__scroll {
    background-color: transparent;
  }
}

.generationBgc {
  .container {
    padding: 0 30rpx 30rpx;

    .title_box {
      font-size: 28rpx;
      color: var(--a-one-text-color);
      font-weight: bold;
      position: relative;
      padding-left: 30rpx;
      margin-top: 40rpx;
      margin-bottom: 18rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translate(0, -50%);
        width: 12rpx;
        height: 18rpx;
        background: var(--a-main-color);
        border-radius: 6rpx;
      }

      .text {
        font-size: 24rpx;
        font-weight: normal;
      }
    }

    .uploadImg {
      position: relative;
      box-sizing: border-box;
      height: 400rpx;
      background: var(--a-main-box-bg-color);
      border-radius: 20rpx;
      margin-top: 22rpx;
      padding: 16rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;

      .imgSty {
        display: block;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #FFF, $alpha: 0.2);
      }

      .upload_btn {
        text-align: center;

        .iconfont {
          display: block;
          font-size: 36rpx;
          color: var(--a-main-color);
        }

        .text {
          margin-top: 5rpx;
          font-size: 32rpx;
          color: var(--a-three-text-color);
        }

      }

    }

    .scene_box {
      margin-top: 30rpx;

      .tabs {
        display: flex;
        align-items: center;

        .tab {
          box-sizing: border-box;
          flex: 1;
          height: 64rpx;
          font-size: 30rpx;
          font-weight: bold;
          border-radius: 32rpx;
          color: var(--a-three-text-color);

          display: flex;
          align-items: center;
          justify-content: center;

          &.active {
            color: var(--a-main-color);
            border: 2rpx solid var(--a-main-color);
          }
        }
      }

      .scene_content {
        margin-top: 20rpx;

        .scene_list {
          display: grid;
          grid-template-rows: repeat(2, 220rpx);
          grid-template-columns: repeat(auto-fill, 160rpx);
          gap: 17rpx;
          overflow-x: auto;
          overflow-y: hidden;
          max-height: 460rpx;
          margin-top: 20rpx;

          &.gird {
            grid-auto-flow: column;
          }

          &.noTowRows {
            grid-template-rows: repeat(1, 220rpx);
          }

          &::-webkit-scrollbar {
            display: none;
          }

          .scene_item {
            flex-shrink: 0;
            width: 160rpx;
            font-size: 28rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 12rpx;
            color: var(--a-three-text-color);

            &.active {
              color: var(--a-main-color);

              .scene_img {
                border: 4rpx solid var(--a-main-color);
              }
            }

            .scene_img {
              box-sizing: border-box;
              width: 160rpx;
              height: 160rpx;
              border-radius: 30rpx;
              border: 4rpx solid transparent;
            }
          }

        }

        .textarea {
          margin-top: 30rpx;
          position: relative;

          .ai_create_btn {
            position: absolute;
            right: 16rpx;
            bottom: 16rpx;
            z-index: 2;
            width: 134rpx;
            height: 43rpx;
            background: #57547B;
            border-radius: 23rpx;
            font-size: 20rpx;
            color: var(--a-one-text-color);
            border: 1rpx solid rgba(255, 255, 255, 0.6);
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 43rpx;
            gap: 5rpx;

            .iconfont {
              font-size: 24rpx;
            }
          }
        }
      }
    }

    .imgNumList {
      margin-top: 22rpx;
      display: flex;
      align-items: center;
      gap: 18rpx;

      .imgNum_item {
        box-sizing: border-box;
        width: 84rpx;
        height: 84rpx;
        border-radius: 13rpx;
        color: var(--a-one-text-color);
        background: var(--a-main-box-bg-color);
        border: 4rpx solid transparent;
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          color: var(--a-main-color);
          border: 4rpx solid var(--a-main-color);
        }
      }
    }

  }

  .footer {
    .footer_placeholder {
      height: 176rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 176rpx;
      background: var(--a-main-tabNav-bg-color);
      padding: 28rpx 30rpx 0;


      .create_btn {
        height: 86rpx;
        background: var(--a-main-color);
        border-radius: 44rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 30rpx;

        .create_btn_title {
          font-size: 32rpx;
          color: var(--a-one-text-color);
        }

        .create_btn_label {
          font-size: 20rpx;
          color: var(--a-one-text-color);
        }
      }
    }
  }
}
</style>